package com.lill.auth2.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lill.auth2.constant.AuthBean;
import com.lill.auth2.constant.AuthConstant;
import com.lill.common.component.util.AESUtil;

public class TwiceToken {
	
	private final static Logger log = LoggerFactory.getLogger(TwiceToken.class);
	
	public static String createToken(AuthBean beanInfo) {
		String tokenContent="";
		try {
			Map<String, Object> headerClaims=new HashMap<String, Object>();
			headerClaims.put("access",true);
			headerClaims.put("auth","twice");
			Algorithm algorithm=Algorithm.HMAC512(AESUtil.secretKey);
			Builder builder=JWT.create().withHeader(headerClaims).withIssuer(AuthConstant.issuer);
			builder.withExpiresAt(new Date(new Date().getTime()+600*1000));
			builder.withClaim("userId", beanInfo.getUserId());
			builder.withClaim("accessUrl", beanInfo.getAccessUrl());
			builder.withClaim("ipAdress", beanInfo.getIpAdress());
			tokenContent=AESUtil.encrypt16(builder.sign(algorithm));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return tokenContent;
	}
	
	public static AuthBean decryptToken(String token) {
		AuthBean bean=null;
		try {
			Algorithm algorithm=Algorithm.HMAC512(AESUtil.secretKey);
			JWTVerifier verifier=JWT.require(algorithm).build();
			DecodedJWT jwt=verifier.verify(AESUtil.decrypt16(token));
			Map<String, Claim> mapClaim=jwt.getClaims();
			bean=new AuthBean();
			bean.setUserId(mapClaim.get("userId").asString());
			bean.setAccessUrl(mapClaim.get("accessUrl").asString());
			bean.setIpAdress(mapClaim.get("ipAdress").asString());
		} catch (Exception e) {
			bean=null;
			log.error(e.getMessage(), e);
		}
		return bean;
	}
	
}
